/*
 * @Descripttion : tag
 * @Author       : QianFox Team
 * @Date         : 2022-06-17 11:11:02
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2023-02-28 17:06:38
 */

function Tag() {
    this.HANDLE_DELETE = '.foxui-tag-close';
    this.HANDLE_ADD = '.foxui-tag-add';
    this.CONTAINER = '.foxui-tag';
    this.CLOSE = '.foxui-icon-guanbi-o';
    this.INPUT = '.foxui-tag-input';
    // 数据
    this.addBtn = '';
    this.class = '';
    this.hasClose = false;
    this.text = '';
}

Tag.prototype._init = function () {
    this._bindClose();
    this._bindAdd();
};

Tag.prototype._bindClose = function () {
    let that = this;
    $(document).on('click', this.HANDLE_DELETE, function () {
        $(this)
            .closest(that.CONTAINER)
            .fadeOut(function () {
                $(this).remove();
            });
    });
};

Tag.prototype._bindAdd = function () {
    let that = this;
    // 点击添加
    $(document).on('click', this.HANDLE_ADD, function () {
        let $this = $(this),
            $container = $this.prev(that.CONTAINER),
            height = $this.height(),
            width = $this.width(),
            len = $container.find(that.CLOSE).length,
            type = $this.attr('data-type') ? $this.attr('data-type') : '',
            size = $this.attr('data-size') ? $this.attr('data-size') : '',
            hasClose = len > 0 ? true : false;

        // 保存数据 -> 添加按钮
        that.addBtn = this;
        // 保存数据 -> 标签 class
        if (type || size) {
            type = type ? 'foxui-' + type : '';
            size = size ? 'foxui-size-' + size : '';
            that.class = type + ' ' + size;
        } else {
            that.class = $container.attr('class');
        }
        // 保存数据 -> 是否有关闭按钮
        hasClose && (that.hasClose = hasClose);

        $this.before(`<input class="foxui-tag-input" style="height:${height}px; width:${width + 20}px"/>`);
        $this.prev('.foxui-tag-input').focus();
        $this.remove();
    });

    // 输入框失去焦点
    $(document).on('blur', this.INPUT, function () {
        let $this = $(this);

        that.text = $(this).val();
        if (that.text) {
            $this.before(that._addHtml());
        }
        $this.after(that.addBtn);
        $this.remove();
        // 重置数据
        that._resetData();
    });

    // 输入框按回车键
    $(document).on('keydown', this.INPUT, function (event) {
        if (event.keyCode === 13) {
            $(this).blur();
        }
    });
};

Tag.prototype._addHtml = function () {
    return [`<span class="foxui-tag ${this.class}">`, `${this.text}`, `${this.hasClose ? '<i class="foxui-tag-close foxui-icon-guanbi-o"></i>' : ''}`, '</span>'].join('');
};

Tag.prototype._resetData = function () {
    this.addBtn = '';
    this.class = '';
    this.hasClose = false;
    this.text = '';
};

let tag = new Tag();

export { tag };
